﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using Common;
using ModelLibrary;
using System.Windows.Forms;
using System.Collections;

namespace DataBaseBackupTools.FmChild
{
    public partial class FmTaskChild : Form
    {
        public FmTaskChild()
        {
            InitializeComponent();
            FmTaskChild_Load();
        }
        /// <summary>
        /// 选择执行周期时当前应该显示的Panel
        /// </summary>
        private string ActionCycle_ViewPanelNow { get { return _ActionCycle_ViewPanelNow; } set { _ActionCycle_ViewPanelNow = value; } }
        private string _ActionCycle_ViewPanelNow = "plTimeStack";
        private List<MyDict> listDict { get { return _listDict; } set { _listDict = value; } }
        private List<MyDict> _listDict = new List<MyDict>();

        public List<Instance> LiInst { get { return _LiInst; } set { _LiInst = value; } }
        private List<Instance> _LiInst = null;
        private void FmTaskChild_Load()//新建窗口初始化
        {
            listDict.Add(new MyDict("database_name", "数据库名称"));
            listDict.Add(new MyDict("database_id", "数据库ID"));
            listDict.Add(new MyDict("compatibility_level", "兼容级别"));
            listDict.Add(new MyDict("create_date", "创建日期"));
            listDict.Add(new MyDict("state_desc", "数据库状态"));
            listDict.Add(new MyDict("recovery_model_desc", "恢复模式"));
            listDict.Add(new MyDict("filename", "数据库文件存放位置"));
            listDict.Add(new MyDict("version", "当前数据库版本"));
            listDict.Add(new MyDict("Checked", "选择"));
            //listDict.Add(new MyDict("database_name", "数据库名称"));
            //listDict.Add(new MyDict("database_name", "数据库名称"));
            //listDict.Add(new MyDict("database_name", "数据库名称"));
            //listDict.Add(new MyDict("database_name", "数据库名称"));
            //listDict.Add(new MyDict("database_name", "数据库名称"));
            //listDict.Add(new MyDict("database_name", "数据库名称"));
            //listDict.Add(new MyDict("database_name", "数据库名称"));

            this.WindowState = FormWindowState.Maximized;
            this.cbbBackupType.DataSource = AppSets.BackupType;
            this.cbbBackupType.SelectedIndex = 0;

            dtpStartDateTime.CustomFormat = AppSets.TimeFormatString;
            dtpActionDateTime.CustomFormat = AppSets.TimeFormatString;

            List<string> ActCycle = new List<string>();
            for (int i = 0; i < AppSets.TypeOfActionCycle.Length; i++)
            {
                ActCycle.Add(AppSets.TypeOfActionCycle[i][1]);
            }
            this.cbbTypeOfActionCycle.DataSource = ActCycle.ToArray();
            this.cbbTypeOfActionCycle.SelectedIndex = 0;
            if (System.IO.File.Exists(AppSets.InstancePath))
            {
                LiInst = XmlHelper.XmlDeserializeFromFile<LiInstances>(AppSets.InstancePath, AppSets.Encodings);
                this.cbbInstanceSelect.DataSource = LiInst;
                this.cbbInstanceSelect.DisplayMember = "taskName";
                this.cbbInstanceSelect.ValueMember = "taskName";
            }
            this.cbbDatabaseSelectRange.DataSource = AppSets.DatabaseSelectRange;
            this.cbbDatabaseSelectRange.SelectedIndex = 0;

            foreach (DataGridViewColumn columns in this.dgvDatabaseSelect.Columns)
            {
                columns.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }
            this.dgvDatabaseSelect.CellValueChanged += DgvDatabaseSelect_CellValueChanged;
            this.dgvDatabaseSelect.CurrentCellDirtyStateChanged += dgvDatabaseSelect_CurrentCellDirtyStateChanged;


        }

        private void btnSave_Click(object sender, EventArgs e)//保存按钮
        {
            BackupTasks bktk = new BackupTasks();
            bktk.tabPageTotal = backupValueFromApp<tabPageTotal>(bktk.tabPageTotal, this.tabControl1);
            bktk.tabPagePeriod = backupValueFromApp<tabPagePeriod>(bktk.tabPagePeriod, this.tabControl1);


            XmlHelper.XmlSerializeToFile(bktk, AppSets.BackupPath, AppSets.Encodings);
        }

        private void btnCancel_Click(object sender, EventArgs e)//取消按钮
        {
            this.Close();
        }

        private void cbbTypeOfActionCycle_SelectedIndexChanged(object sender, EventArgs e)//选执行周期的类型时
        {
            ViewPanel(cbbTypeOfActionCycle.SelectedItem.ToString());
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)//选择选项卡时
        {
            if (tabControl1.SelectedIndex == 2)
            {

            }
        }

        private void cbbDatabaseSelectRange_SelectedIndexChanged(object sender, EventArgs e)//备份数据库选择页面,根据总体设置里面的实例选择数据库，
        {
            ViewDatabaseSelections(cbbDatabaseSelectRange.SelectedItem.ToString());
            this.rtbDatabaseSelect.Text = "";
        }
        private void ViewDatabaseSelections(string selectRange)//备份数据库选择页面,根据总体设置的实例选择数据库
        {
            string ViewAllDatabases = "SELECT a.name AS database_name,a.database_id,a.compatibility_level,a.create_date,a.state_desc,a.recovery_model_desc,b.filename,b.version FROM sys.databases a JOIN sysdatabases b ON a.name=b.name";
            string ViewUserDatabases = ViewAllDatabases + " WHERE a.database_id>4";
            string ViewSysDatabases = ViewAllDatabases + " WHERE a.database_id<5";
            string SqlString;
            if (selectRange == "AllDatabase")
            {
                SqlString = ViewAllDatabases;
            }
            else if (selectRange == "UserDatabase")
            {
                SqlString = ViewUserDatabases;
            }
            else if (selectRange == "SysDatabase")
            {
                SqlString = ViewSysDatabases;
            }
            else
                SqlString = "";

            DataTable dt = new DataTable();
            Instance inst = new Instance();
            if (this.cbbInstanceSelect.SelectedValue == null)
            {
                this.dgvDatabaseSelect.DataSource = dt;
                return;
            }
            foreach (Instance item in LiInst)
            {
                if (item.taskName == this.cbbInstanceSelect.SelectedValue.ToString())
                {
                    inst = item;
                    break;
                }
            }

            SqlHelper sh = new SqlHelper(inst);
            if (sh.connectionStatus)
            {
                dt = sh.TableReads(SqlString);
            }
            if (dt.Rows.Count > 0)
            {
                dt.Columns.Add("Checked", typeof(bool));
                dt.Columns["Checked"].SetOrdinal(0);
                this.dgvDatabaseSelect.DataSource = dt;
                foreach (DataGridViewColumn columns in this.dgvDatabaseSelect.Columns)
                {
                    columns.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                }
            }
            this.dgvDatabaseSelect.Columns["database_id"].Visible = false;
            ReNameDataGridView(dgvDatabaseSelect);
        }
        private void dgvDatabaseSelect_CurrentCellDirtyStateChanged(object sender, EventArgs e)//值变化后，实时更新
        {
            if (dgvDatabaseSelect.IsCurrentCellDirty)
            {
                dgvDatabaseSelect.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }
        private void DgvDatabaseSelect_CellValueChanged(object sender, EventArgs e)//勾选checked列时,将数据库名写入rtbDatabaseSelect
        {
            string selectDatabase = this.dgvDatabaseSelect["database_name", this.dgvDatabaseSelect.CurrentCell.RowIndex].Value.ToString();
            if ((bool)this.dgvDatabaseSelect.CurrentCell.Value)
            {
                this.rtbDatabaseSelect.Text += this.rtbDatabaseSelect.Text == "" ? selectDatabase : "," + selectDatabase;
            }
            else
            {
                this.rtbDatabaseSelect.Text = this.rtbDatabaseSelect.Text.Replace(selectDatabase, "");
                this.rtbDatabaseSelect.Text = this.rtbDatabaseSelect.Text.Replace(",,", ",");
                if (this.rtbDatabaseSelect.Text.StartsWith(","))
                {
                    this.rtbDatabaseSelect.Text = this.rtbDatabaseSelect.Text.Substring(1);
                }
            }
        }
        private void ReNameDataGridView(DataGridView dgv)//重命名列名
        {
            foreach (DataGridViewColumn item in dgv.Columns)
            {
                if (listDict.Where(MyDict => MyDict.Key == item.Name).Select(MyDict => MyDict.Value).ToList().Count > 0)
                {
                    item.HeaderText = listDict.Where(MyDict => MyDict.Key == item.Name).Select(MyDict => MyDict.Value).ToList()[0].ToString();
                }
            }
        }
        private void ViewPanel(string ActionCycle)//时间周期设置页面,查看指定Panel
        {
            string ViewPanelLast = "";
            bool LastOk = false;
            bool NowOk = false;
            for (int i = 0; i < AppSets.TypeOfActionCycle.Length; i++)
            {
                if (AppSets.TypeOfActionCycle[i][1] == ActionCycle)
                {
                    ViewPanelLast = ActionCycle_ViewPanelNow;
                    ActionCycle_ViewPanelNow = AppSets.TypeOfActionCycle[i][0];
                    break;
                }
            }
            foreach (Panel plItem in plDynamic.Controls)
            {
                if (plItem.Name == ViewPanelLast && !LastOk)
                {
                    plItem.Visible = false;
                    LastOk = true;
                }
                if (plItem.Name == ActionCycle_ViewPanelNow && !NowOk)
                {
                    plItem.Visible = true;
                    plItem.Dock = DockStyle.Fill;
                    NowOk = true;
                }
                if (NowOk && LastOk)
                {
                    return;
                }
            }
        }


        /// <summary>
        /// 根据TabControl，返回各个页面对应的类
        /// </summary>
        /// <typeparam name="T">页面对应类</typeparam>
        /// <param name="shuxing">页面对应类名称</param>
        /// <param name="tc">要检索的TabControl</param>
        /// <returns>返回页面对应类型</returns>
        private T backupValueFromApp<T>(T shuxing, TabControl tc)
        {
            foreach (TabPage tp in tc.Controls)
            {
                if (shuxing.GetType().Name.ToString() == tp.Name)
                {
                    shuxing = TabPageValueFromApp<T>(shuxing, tp);
                    return shuxing;
                }
            }

            return shuxing;
        }
        /// <summary>
        ///     返回页面内对应类型属性
        /// </summary>
        /// <typeparam name="T">传入类型</typeparam>
        /// <param name="shuxing">类型值</param>
        /// <param name="ctrs">指定的TabPage，以及递归时的传入容器控件</param>
        /// <returns>对应类型的值</returns>
        private T TabPageValueFromApp<T>(T shuxing, Control ctrs)
        {
            foreach (Control ctr in ctrs.Controls)
            {
                if (ctr.Name.StartsWith("tb"))//TextBox
                {
                    if (shuxing.GetType().GetProperty(ctr.Name.Substring(2)).PropertyType.Name == "Int32")
                    {
                        shuxing.GetType().GetProperty(ctr.Name.Substring(2)).SetValue(shuxing, Convert.ToInt32(ctr.Text), null);
                    }
                    else
                        shuxing.GetType().GetProperty(ctr.Name.Substring(2)).SetValue(shuxing, ctr.Text, null);
                }
                else if (ctr.Name.StartsWith("cbb"))//ComboBox
                {
                    shuxing.GetType().GetProperty(ctr.Name.Substring(3)).SetValue(shuxing, ctr.Text, null);
                }
                else if (ctr.Name.StartsWith("rtb"))//RichTextBox
                {
                    shuxing.GetType().GetProperty(ctr.Name.Substring(3)).SetValue(shuxing, ctr.Text, null);
                }
                else if (ctr.Name.StartsWith("dtp"))//DateTimePicker
                {
                    shuxing.GetType().GetProperty(ctr.Name.Substring(3)).SetValue(shuxing, ctr.Text, null);
                }
                else if (ctr.Name.StartsWith("pl") && ctr.Visible)//Panel
                {
                    shuxing = (T)TabPageValueFromApp<T>(shuxing, ctr);
                }
                else if (ctr.Name.StartsWith("clb"))//CheckedListBox
                {
                    ListMyDict dict = new ListMyDict();
                    MyDict myDict;
                    for (int i = 0; i < ((CheckedListBox)ctr).CheckedItems.Count; i++)
                    {
                        myDict = new MyDict(((CheckedListBox)ctr).CheckedItems[i].ToString(), true);
                        dict.Add(myDict);
                    }
                    shuxing.GetType().GetProperty(ctr.Name.Substring(3)).SetValue(shuxing, dict, null);
                }
            }


            return (T)shuxing;
        }


        private void tbBackupPath_DoubleClick(object sender, EventArgs e)//总体设置页面双击备份位置
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            //fbd.RootFolder=
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                this.tbBackupPath.Text = fbd.SelectedPath; ;
            }
        }
    }
}
